package com.example.yuwei.registerlogin_system;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.SharedPreferences;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * LoginActivity
 *
 * @author yuwei
 * @date 2019/1/10
 */
public class LoginActivity extends AppCompatActivity {
    private EditText mUserName;
    private EditText mPassWord;
    private Button mBtnLogin;
    private String username;
    private String password;
    private final int CONNECT_ERROR = 0;
    private final int SUCCESS = 1;
    private final int FAILURE = 2;
    private final int URL_ISEMPTY = 3;
    private final int CONNECT_TIMEOUT = 4;
    String loginUrl = "http://192.168.94.110:8080/login/json/data";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    /**
     * 注册按钮的响应
     *
     * @param view
     */
    public void register(View view) {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

    public void init() {
        mUserName = findViewById(R.id.username);
        mPassWord = findViewById(R.id.password1);
        mBtnLogin = findViewById(R.id.Login_Button);
        //登录按键的响应
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkOut();
                setLogin();
            }
        });
    }

    /**
     * 检查用户的输入是否为空
     */
    public void checkOut() {
        username = mUserName.getText().toString().trim();
        password = mPassWord.getText().toString().trim();

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(LoginActivity.this, getResources().getString(R.string.username_is_empty), Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(LoginActivity.this, getResources().getString(R.string.pass_is_empty), Toast.LENGTH_SHORT).show();
            return;
        }
    }

    /**
     * 发送用户的信息给服务器
     */
    public void setLogin() {
        String[] data = new String[]{username, password};
        @SuppressLint("HandlerLeak") Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case CONNECT_ERROR:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.error_connect), Toast.LENGTH_SHORT).show();
                        break;
                    case SUCCESS:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.login_success), Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(LoginActivity.this, webActivity.class));
                        LoginActivity.this.finish();
                        break;
                    case FAILURE:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.login_fail), Toast.LENGTH_SHORT).show();
                        break;
                    case URL_ISEMPTY:
                        Log.e("input error", "url为空");
                        break;
                    case CONNECT_TIMEOUT:
                        Toast.makeText(LoginActivity.this, getResources().getString(R.string.connect_timeout), Toast.LENGTH_SHORT).show();
                        break;
                    default:
                }
            }
        };
        OperateData operateData = new OperateData();
        String jsonString = operateData.stringTojson(data);
        URL url = null;
        try {
            url = new URL(loginUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        operateData.sendData(jsonString, handler, url);
    }

    /**
     * 通过用户名返回密码，没有密码则返回  “”
     *
     * @param key
     * @return
     */
    public String getSharedPreference(String key) {
        String regularEx = "#";
        String[] str = null;
        SharedPreferences sp = getSharedPreferences("loginInfo", MODE_PRIVATE);
        String values;
        values = sp.getString(key, "");

        str = values.split(regularEx);

        if (str.length > 1) {
            return str[1];
        } else {
            return "";
        }
    }

    /**
     * 将登录的状态保存到sharedpreference
     */

    private void saveLoginStatus(boolean status, String username) {

        // loginInfo表示文件名
        SharedPreferences sp = getSharedPreferences("loginInfo", MODE_PRIVATE);
        //获取编辑器
        SharedPreferences.Editor editor = sp.edit();
        //存入登录状态
        editor.putBoolean("islogin", status);
        //提交修改
        editor.commit();
    }

    /**
     * 判断是否存在用户名
     */
    private boolean isExistUsername(String username) {
        boolean hasUsername = false;
        String str = getSharedPreference(username);
        if (str != null && !(str.equals(""))) {
            hasUsername = true;
            System.out.println(str);
        }

        return hasUsername;

    }
}
